//
//  HHYApplyPZVC.m
//  大股票
//
//  Created by apple on 2019/9/5.
//  Copyright © 2019 apple. All rights reserved.
//

#import "HHYApplyPZVC.h"

#import "XieYiViewController.h"


#define kTypeNameArr @[@"3倍" , @"4倍", @"5倍", @"6倍", @"7倍", @"8倍", @"9倍", @"10倍"]
#define  kMainNotiNames @[UITextFieldTextDidChangeNotification]
//M
#import "HHYLocalApplyPZModel.h"
//VC
#import "HHYConfirePayVC.h"

@interface HHYApplyPZVC ()<UITextFieldDelegate>
//bigSV
@property (nonatomic, strong) UIScrollView *bigSV;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) UIView *contentView;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *titleLabelArr;
//本金tf
@property (weak, nonatomic) IBOutlet UITextField *bjTF;
//倍数按钮
@property (weak, nonatomic) IBOutlet UIButton *unitBtn;

@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *outTFArr;
@property (weak, nonatomic) IBOutlet UILabel *totalAmountLabel;

@property (nonatomic, strong) HHYLocalApplyPZModel *currentApplyModel;

@property (nonatomic, strong) UIButton *sureBtn;

@property (weak, nonatomic) IBOutlet UILabel *xieYiLabel;


@end

@implementation HHYApplyPZVC

- (instancetype)initWithType:(NSInteger)type {
    self = [self init];
    if (self) {
        _type = type;
        _currentApplyModel = [HHYLocalApplyPZModel new];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setupSubViews];
    
    //    [self setupSubViews];
    
    [self addNoti];
    
    [self computeAction];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    self.xieYiLabel.userInteractionEnabled = YES;
    
    [self.xieYiLabel addGestureRecognizer:tap];
}

#pragma mark - tapGestureAction
- (void)tapGestureAction:(UITapGestureRecognizer *)tap {
    if (@available(iOS 11.0, *)) {
        //防止多次触发事件
        __block UIView *blockView = tap.view;
        blockView.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            blockView.userInteractionEnabled = YES;
        });
    }
    
    if (tap.view == self.xieYiLabel) {
        XieYiViewController *xy = [XieYiViewController new];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"scsdcas" ofType:@"txt"];
        NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        xy.xieyi = str;
        [self presentViewController:xy animated:YES completion:nil];
        return;
    }
    
}

#pragma mark - 通知
- (void)addNoti {
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction:) name:kAppLoginOther object:nil];
    for (NSString *notiName in kMainNotiNames) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction:) name:notiName object:nil];
        
    }
}

- (void)removeNoti {
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:kAppLoginOther object:nil];
    for (NSString *notiName in kMainNotiNames) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:notiName object:nil];
    }
}

- (void)notiAction:(NSNotification *)noti {
    if ([noti.name isEqualToString:UITextFieldTextDidChangeNotification]) {
        [self computeAction];
        return;
    }
}

-(void)dealloc {
    [self removeNoti];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //    //2.0
    self.sureBtn.frame = CGRectMake(0, self.view.xl_height-hhy_kTabbarSafeBottomMargin-48, hhy_kScreenWidth,48);
    self.bigSV.frame = CGRectMake(0, 0, hhy_kScreenWidth, CGRectGetMinY(self.sureBtn.frame));
}

- (void)createNavi {
    [self setupNavi_White];
    self.navigationItem.title = @"配资申请";
}

- (IBAction)unitAction:(id)sender {
    [self showAlertView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self createNavi];
    
}





- (void)setupSubViews {
    

    [self.view addSubview:self.bigSV];
    [self.view addSubview:self.sureBtn];

    [self.bigSV addSubview:self.contentView];
    
    //
    if (@available(iOS 11.0, *)) {
        self.bigSV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self updateUIAfterLoadNib];
    
    //隐藏键盘
    UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidekeyBoardAction)];
    [self.view addGestureRecognizer:tap];
}

#pragma mark - 创建rightView
- (UIView *)createRightViewWithTitle:(NSString *)title {
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 28)];
    leftLabel.textColor = rgba(153, 153, 153, 1);
    leftLabel.font = [UIFont systemFontOfSize:16];
    leftLabel.textAlignment = NSTextAlignmentCenter;
    leftLabel.text = title;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 28)];
    [view addSubview:leftLabel];
    return view;
}

- (void)updateUIAfterLoadNib {
    //禁用点击
    for (UITextField *tf in self.outTFArr) {
        tf.enabled = NO;
        tf.rightViewMode = UITextFieldViewModeAlways;
        tf.rightView = [self createRightViewWithTitle:@"元"];
        tf.textColor = rgba(151, 151, 151, 1.0);
    }
    
//    self.bjTF.enabled = NO;
    self.bjTF.rightViewMode = UITextFieldViewModeAlways;
    self.bjTF.rightView = [self createRightViewWithTitle:@"元"];
    
    for (UILabel *label in self.titleLabelArr) {
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
        NSArray *componets = [label.text componentsSeparatedByString:@" "];
        NSRange range1 = [label.text rangeOfString:componets.firstObject];
        NSRange range2 = [label.text rangeOfString:componets.lastObject];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:range1];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:range2];
        label.attributedText = str;
    }
    
}

#pragma mark - 展示选择弹出框
- (void)showAlertView {
    
    //UIAlertController风格：UIAlertControllerStyleAlert
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择倍数"
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet ];
    
    //    alertController.popoverPresentationController.sourceView = self.babyIV;
    //    alertController.popoverPresentationController.sourceRect = self.babyIV.bounds;
    
    //添加确定到UIAlertController中
    __weak typeof(self)wSelf = self;
    for (NSString *type in kTypeNameArr) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:type style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            __strong typeof(self)sSelf = wSelf;
            [sSelf chooseActionWithTitle:action.title];
        }];
        [alertController addAction:action];
    }
    //添加取消到UIAlertController中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)chooseActionWithTitle:(NSString *)title {
    [self.unitBtn setTitle:title forState:UIControlStateNormal];
    [self computeAction];
}

#pragma mark - btnActions
- (void)btnActions:(UIButton *)btn {
    if (@available(iOS 11.0, *)) {
        //防止多次触发事件
        __block UIButton *blockBtn = btn;
        blockBtn.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            blockBtn.userInteractionEnabled = YES;
        });
    }
    
    if (self.sureBtn == btn) {
        [self submitAction];
        return;
    }
    
}

#pragma mark - 计算
- (void)computeAction {
    NSInteger bj = [self.bjTF.text integerValue];

    if (bj % 100 != 0) {
        return;
    }
    NSInteger unit = [self.unitBtn.titleLabel.text integerValue];
    self.currentApplyModel.beiShu = unit;

    self.currentApplyModel.tzbj = [NSString stringWithFormat:@"%ld", bj];
    
    
    
    NSInteger pzzj = unit * bj;
    NSInteger totalZj = bj+pzzj;
    NSInteger ksjjx = pzzj + 0.5*bj;
    NSInteger kspcx = pzzj + 0.2*bj;
    float glf = 0;
    switch (_type) {
        case 1:
        {
            glf = 0.06/100.0*pzzj;
        }
            break;
        case 2:
        {
            glf = 0.14/100.0*pzzj;
        }
            break;
        case 3:
        {
            glf = 0.6/100.0*pzzj;
        }
            break;
        default:
            break;
    }
    
    float pay = bj+glf;
    
    //刷新UI
    UITextField *pzTF = self.outTFArr[0];
    self.currentApplyModel.pzzj = [NSString stringWithFormat:@"%ld", pzzj];
    pzTF.text = [NSString stringWithFormat:@"%ld", pzzj];
    
    UITextField *totalZjTF = self.outTFArr[1];
    self.currentApplyModel.totalBJ = [NSString stringWithFormat:@"%ld", totalZj];
    totalZjTF.text = [NSString stringWithFormat:@"%ld", totalZj];
    
    UITextField *ksjjxTF = self.outTFArr[2];
    self.currentApplyModel.kuisun1 = [NSString stringWithFormat:@"%ld", ksjjx];
    ksjjxTF.text = [NSString stringWithFormat:@"%ld", ksjjx];
    
    UITextField *kspcxTF = self.outTFArr[3];
    self.currentApplyModel.kuisun2 = [NSString stringWithFormat:@"%ld", kspcx];
    kspcxTF.text = [NSString stringWithFormat:@"%ld", kspcx];
    
    UITextField *glfTF = self.outTFArr[4];
    self.currentApplyModel.glf = [NSString stringWithFormat:@"%0.2f", glf];
    glfTF.text = [NSString stringWithFormat:@"%0.2f", glf];
    
    self.totalAmountLabel.text = [NSString stringWithFormat:@"共应支付 %0.2f元", pay];
}

#pragma mark - 提交
- (void)submitAction {
    NSInteger bj = [self.bjTF.text integerValue];
    if (bj % 100 != 0 || bj ==0) {
        [HHYUtils textExampleLong:@"请输入100的整数"];
        return;
    }
    
    CGFloat pay = [self.currentApplyModel.glf floatValue] + [self.currentApplyModel.tzbj integerValue];
    //扣费
    if ([DGPUtil money]  < pay) {
        [HHYUtils textExampleLong:@"余额不足"];
        return;
    }
    
    //保存模型
    self.currentApplyModel.createTime = [[NSDate date] timeIntervalSince1970];
    self.currentApplyModel.user = [DGPUtil getCurrentUserID];
//    [self.currentApplyModel saveOrUpdate];
    //跳转
    HHYConfirePayVC *payVC = [HHYConfirePayVC new];
    payVC.applyModel = self.currentApplyModel;
    [self.navigationController pushViewController:payVC animated:YES];
    
}

#pragma mark - getter
- (UIScrollView *)bigSV {
    if (!_bigSV) {
        _bigSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, hhy_kScreenWidth, hhy_kScreenHeight-hhy_kStatusBarAndNavigationBarHeight-hhy_kTabbarSafeBottomMargin)];
        //        mysssSV.delegate = self;
        //        _bigSV.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _bigSV.backgroundColor = [UIColor clearColor];
        _bigSV.showsHorizontalScrollIndicator = NO;
        _bigSV.showsVerticalScrollIndicator = NO;
        
        //contentSize
        _bigSV.contentSize = CGSizeMake(0, self.contentView.xl_height);
    }
    return _bigSV;
}

- (UIView *)contentView {
    if (!_contentView) {
        UINib *nib = [UINib nibWithNibName:@"HHYApplyPZView" bundle:nil];
        NSArray *objs = [nib instantiateWithOwner:self options:nil];
        _contentView = objs[0];
        _contentView.frame = CGRectMake(0, 0, hhy_kScreenWidth, 764);
    }
    return _contentView;
}

- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _sureBtn.frame = CGRectMake(0, hhy_kScreenHeight-hhy_kStatusBarHeight-hhy_kTabbarSafeBottomMargin, hhy_kScreenWidth,48);
        _sureBtn.backgroundColor = rgba(255, 77, 0, 1);
        [_sureBtn setTitle:@"立即申请" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(btnActions:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

@end
